(defun openConnection (ip port)
  (SOCKET:SOCKET-CONNECT port ip)
)

(defun receiveDescription (socketStream)
  (do ((description (READ-LINE socketStream)))
    (description (parseDescription description))
    (setf description (READ-LINE socketStream))
  )
)

(defun parseDescription (description)
  (let* ((splitDescription (splitString description #\;))
         (numPegs (parse-integer (car splitDescription)))
         (colorList (splitString (cadr splitDescription) #\,)))
    (values numPegs colorList)
  )
)

(defun splitString (string delimiter)
  (let ((delimiterPos (position delimiter string)))
    (if (null delimiterPos)
      (list string)
      (append (list (subseq string 0 delimiterPos))
              (splitString (subseq string (+ 1 delimiterPos)) delimiter))
    )
  )
)

(defun sendGuess (socketStream guess)
  (format socketStream "~a~%" guess)
  (FINISH-OUTPUT socketStream)
)

(defun receiveResult (socketStream)
  (do ((result (READ-LINE socketStream)))
    (result (parseResult result))
    (setf result (READ-LINE socketStream))
  )
)

(defun parseResult (result)
  (let* ((splitResult (splitString result #\,))
         (numRed (parse-integer (car splitResult)))
         (numWhite (parse-integer (cadr splitResult))))
    (values numRed numWhite)
  )
)

(defun samplePlayer (ip port)
  (let* ((server (openConnection ip port)))
    ;read the problem description from the server
    (multiple-value-bind (numPegs colorList) (receiveDescription server)
      ;send an initial guess
      (sendGuess server (randomGuess numPegs colorList))
    
      ;get a result from the server
      ;this should be nil on the first call
      (do ((result (receiveResult server)))
        ;stop when the result has all pegs as red pegs
        ((multiple-value-bind (numRed) result (= numRed numPegs)))
        
        ;otherwise process the result
        nil
        
        ;then send a new guess
        (sendGuess server (randomGuess numPegs colorList))
      )
    )
  )
)

(defun randomGuess (numPegs colorList)
  (do ((peg 0 (+ peg 1))
       (guess ""))
      ((= peg numPegs) guess)
    (setf guess (concatenate 'string guess (nth (random (length colorList)) colorList)))
    (if (< peg (- numPegs 1))
      (setf guess (concatenate 'string guess ","))
    )
  )
)